<?php

class Myzen_User {
  
  //this one is stored directly in the base in a structured format
  protected $_email;
  
  //this one is stored in the blob
  protected $_pseudo;
 
  //database setting
  static protected $_dbUserCredentialTableName = 'userCredential';
  static protected $_dbUserCredentialIdCol = 'id';
  static protected $_dbUserCredentialEmailCol = 'email'; 
  static protected $_dbUserCredentialPseudoCol = 'pseudo';  

    static protected $_limitPage = 1000;
  
	static protected $_allowedSearchMode = array('pseudo','email');
    static protected $_allowedWhereCondition = array('begin','end','anywhere');
  
	//user can be identified in different ways:
	//either by an id, an email or a pseudo
    
  public function __construct($identificationData,$data = array()) {
    if(empty($data)) {

    	$db = Zend_Registry::get('dt_dbs')->getDb('user','details','key');	
      	$select = $db->select()->from(self::$_dbUserCredentialTableName);
    	
    	
    	if(!empty($identificationData['id'])) {
	    	$validator = new Zend_Validate_Digits();
    		if (!$validator->isValid($identificationData['id'])) {
      			throw new Zend_Auth_Exception('identifier is invalid');
    		}
      		$select->where($db->quoteInto(self::$_dbUserCredentialIdCol ." = ?", $identificationData['id']));
    	} elseif(!empty($identificationData['email'])) {
	    	$validator = new Zend_Validate_EmailAddress();
    		if (!$validator->isValid($identificationData['email'])) {
      			throw new Zend_Auth_Exception('email is invalid');
    		}
      	$select->where($db->quoteInto(self::$_dbUserCredentialEmailCol ." = ?", $identificationData['email']));
    	} elseif(!empty($identificationData['pseudo'])) {
    		//only alpha numeric and . for pseudo
    		if (preg_match('/[^0-9a-zA-Z\.]/',$identificationData['pseudo'])) {
      			throw new Zend_Auth_Exception('pseudo is invalid');
    		}
      	$select->where($db->quoteInto(self::$_dbUserCredentialPseudoCol ." = ?", $identificationData['pseudo']));
    	}   	
      	
      	$res = $db->fetchAll($select->__toString());
    	
    	if(empty($res)) {
      		throw new Zend_Auth_Exception('user not found');    		
    	}
    	
    	$data = $res[0];	
    }
    
    $this->_id = $data[self::$_dbUserCredentialIdCol];
    $this->_email = $data[self::$_dbUserCredentialEmailCol];
	$this->_pseudo = $data[self::$_dbUserCredentialPseudoCol];
		
	
   	
  }
  
  public function asArray() {
  	$data = array();
  	$data['id'] = $this->getId();
  	$data['email'] = $this->getEmail();
  	$data['pseudo'] = $this->getPseudo();
  	return $data;
  }


  public function getId() {
    return (int) $this->_id;	
  }
    
  public function getEmail() {
    return $this->_email;	
  }
  

  public function getPseudo() {
    return $this->_pseudo;	
  }


  static public function search($mode,$q,$where,$perPage,$page) {
  	
	if(empty($where)) $where = 'begin';
	
	if(!in_array($mode,self::$_allowedSearchMode)) {
		require_once('Myzen/User/Exception.php');
		throw new Myzen_User_Exception('invalid search mode',78);
	}
  	if(!in_array($where,self::$_allowedWhereCondition)) {
		require_once('Myzen/User/Exception.php');
		throw new Myzen_User_Exception('invalid where condition',79);
	}
	
	$page = self::formatPage($page);
	$perPage = self::formatPerPage($perPage);  
	
    $db = Zend_Registry::get('dt_dbs')->getDb('user','details','key');	
    $select = $db->select()->from(self::$_dbUserCredentialTableName)->limitPage($page, $perPage);

	if($mode == 'email' ) $col = self::$_dbUserCredentialEmailCol; 
	if($mode == 'pseudo' ) $col = self::$_dbUserCredentialPseudoCol;  
	
	if($where == 'begin') $select->where($db->quoteInto($col.' LIKE ?',$q.'%'));
	elseif($where == 'end') $select->where($db->quoteInto($col.' LIKE ?','%'.$q));
	elseif($where == 'anywhere') $select->where($db->quoteInto($col.' LIKE ?','%'.$q.'%'));	
	
    $res = $db->fetchAll($select->__toString());	
	$select->order($col.' ASC');
	
	if(empty($res)) return array();
	
	$users = array();
	foreach($res as $num => $data) {
		$users[] = new Myzen_User('',$data);
	}
	
	return $users;
	

  } //end search
  
  
  
  
  
  	static public function formatPage($page = 1) {
		if(empty($page)) $page = 1;
		$validator = new Zend_Validate_Digits();
		if(!$validator->isValid($page)) {
			require_once('status/objects/Exception.php');
			throw new Myzen_User_Exception('invalid input parameters',15);      	
		}
		if(self::$_limitPage < $page) {
			require_once('status/objects/Exception.php');
			throw new Myzen_User_Exception('page search is limited to '.self::$_limitPage.' pages',15);   	  	
		}

		if($page < 1 ) $page = 1;
		return $page;		
	} //end formatPage

	static public function formatPerPage($perPage = 20) {
		if(empty($perPage)) $perPage = 20;
		$validator = new Zend_Validate_Digits();
		if(!$validator->isValid($perPage)) {
		require_once('status/objects/Exception.php');
		throw new Myzen_User_Exception('invalid input parameters',15);      	
		}
		if($perPage < 1 ) $perPage = 1;
		if($perPage > 100 ) $perPage = 100;
		return $perPage;
	} //end formatPerPage
  
  
  
  /*
  Not needed for the time being

  static public function decodeData($data) {
	
    $decoded = @unserialize(gzinflate(base64_decode($data)));
    if(empty($decoded)) {
      require_once('zend/auth/Exception.php');
      throw new Status_Object_Exception('An issue occured while decoding message',16);
    }  
    return  $decoded;	
  }

  static public function encodeData($data) {
  	if(!is_array($data)) {
  		require_once('zend/auth/Exception.php');
  		throw new Status_Object_Exception('input parameter is not an array',12); 
  	}
    $encoded = @base64_encode(gzdeflate(serialize($data),9));
    if(empty($encoded)) {
    	require_once('zend/auth/Exception.php');
    	throw new Status_Object_Exception('An issue occured while encoding message',17);
    } 
    return $encoded;   	
  }  
  
  */
  
} //end class